<template>
  <LoginFormTitle v-show="getShow" class="enter-x" />
  <Form class="p-4 enter-x" :model="formData" :rules="getFormRules" ref="formRef" v-show="getShow" initialValues
    @keypress.enter="handleLogin">
    <FormItem name="tenantCode" class="enter-x">
      <Input size="large" @input="getOrganizationList" v-model:value="formData.tenantCode"
        placeholder="请输入企业编号" class="fix-auto-fill" />
    </FormItem>
    <FormItem name="account" class="enter-x">
      <Input size="large" @input="getOrganizationList" @keydown.enter="enter" v-model:value="formData.account"
        :placeholder="t('sys.login.userName')" class="fix-auto-fill" />
    </FormItem>
    <FormItem name="organizationName" class="enter-x">
      <!-- <Select size="large" v-model:value="formData.organizationName"
        :options="organization.organizationList" labelInValue @change="handleChangeOrganization"
        placeholder="请选择组织" class="fix-auto-fill" /> -->
      <a-select class="fix-auto-fill" v-model:value="formData.organizationName"
        :options="organization.organizationList" labelInValue @change="handleChangeOrganization"
        placeholder="请选择组织">
      </a-select>
    </FormItem>
    <FormItem name="password" class="enter-x">
      <InputPassword size="large" visibilityToggle v-model:value="formData.password"
        :placeholder="t('sys.login.password')" />
    </FormItem>

    <!--验证码-->
    <!-- <ARow class="enter-x">
      <ACol :span="12">
        <FormItem name="inputCode" class="enter-x">
          <Input size="large" v-model:value="formData.inputCode"
            :placeholder="t('sys.login.inputCode')" style="min-width: 100px" />
        </FormItem>
      </ACol>
      <ACol :span="8">
        <FormItem :style="{ 'text-align': 'right', 'margin-left': '20px' }" class="enter-x">
          <img v-if="randCodeData.requestCodeSuccess" style="margin-top: 2px; max-width: initial"
            :src="randCodeData.randCodeImage" @click="handleChangeCheckCode" />
          <img v-else style="margin-top: 2px; max-width: initial"
            src="../../../assets/images/checkcode.png" @click="handleChangeCheckCode" />
        </FormItem>
      </ACol>
    </ARow> -->

    <ARow class="enter-x">
      <ACol :span="12">
        <FormItem>
          <Checkbox v-model:checked="rememberMe" size="small"  @change="changeRemember">
            {{ t('sys.login.rememberMe') }}
          </Checkbox>
        </FormItem>
      </ACol>
      <!-- <ACol :span="12">
        <FormItem :style="{ 'text-align': 'right' }">
          No logic, you need to deal with it yourself
          <Button type="link" size="small" @click="setLoginState(LoginStateEnum.RESET_PASSWORD)">
            {{ t('sys.login.forgetPassword') }}
          </Button>
        </FormItem>
      </ACol> -->
    </ARow>

    <FormItem class="enter-x">
      <Button type="primary" size="large" block @click="handleLogin" :loading="loading">
        {{ t('sys.login.loginButton') }}
      </Button>
      <!-- <Button size="large" class="mt-4 enter-x" block @click="handleRegister">
              {{ t('sys.login.registerButton') }}
            </Button> -->
    </FormItem>
    <!-- <ARow class="enter-x">
      <ACol :md="8" :xs="24">
        <Button block @click="setLoginState(LoginStateEnum.MOBILE)">
          {{ t('sys.login.mobileSignInFormTitle') }}
        </Button>
      </ACol>
      <ACol :md="8" :xs="24" class="!my-2 !md:my-0 xs:mx-0 md:mx-2">
        <Button block @click="setLoginState(LoginStateEnum.QR_CODE)">
          {{ t('sys.login.qrSignInFormTitle') }}
        </Button>
      </ACol>
      <ACol :md="7" :xs="24">
        <Button block @click="setLoginState(LoginStateEnum.REGISTER)">
          {{ t('sys.login.registerButton') }}
        </Button>
      </ACol>
    </ARow> -->

    <!-- <Divider class="enter-x">{{ t('sys.login.otherSignIn') }}</Divider> -->

    <!-- <div class="flex justify-evenly enter-x" :class="`${prefixCls}-sign-in-way`">
      <a @click="onThirdLogin('github')" title="github"><GithubFilled /></a>
      <a @click="onThirdLogin('wechat_enterprise')" title="企业微信"> <icon-font class="item-icon" type="icon-qiyeweixin3" /></a>
      <a @click="onThirdLogin('dingtalk')" title="钉钉"><DingtalkCircleFilled /></a>
      <a @click="onThirdLogin('wechat_open')" title="微信"><WechatFilled /></a>
    </div> -->
  </Form>
  <!-- 第三方登录相关弹框 -->
  <ThirdModal ref="thirdModalRef"></ThirdModal>
</template>
<script lang="ts" setup>
  import {
    reactive,
    ref,
    toRaw,
    unref,
    computed,
    onMounted,
    nextTick
  } from 'vue';

  import {
    Checkbox,
    Form,
    Input,
    Row,
    Col,
    Button,
    Divider,
    Select
  } from 'ant-design-vue';
  import {
    GithubFilled,
    WechatFilled,
    DingtalkCircleFilled,
    createFromIconfontCN
  } from '@ant-design/icons-vue';
  import LoginFormTitle from './LoginFormTitle.vue';
  import ThirdModal from './ThirdModal.vue';
  import {
    useI18n
  } from '/@/hooks/web/useI18n';
  import {
    useMessage
  } from '/@/hooks/web/useMessage';

  import {
    useUserStore
  } from '/@/store/modules/user';
  import {
    LoginStateEnum,
    useLoginState,
    useFormRules,
    useFormValid
  } from './useLogin';
  import {
    useDesign
  } from '/@/hooks/web/useDesign';
  import {
    getCodeInfo,
    getTenantList,
    basBusinessOrganization,
    queryOrganizationByTenantAndUser
  } from '/@/api/sys/user';
  import {localStorage} from '/@/utils/store/locaStore'
  //import { onKeyStroke } from '@vueuse/core';

  const ACol = Col;
  const ARow = Row;
  const FormItem = Form.Item;
  const InputPassword = Input.Password;
  const IconFont = createFromIconfontCN({
    scriptUrl: '//at.alicdn.com/t/font_2316098_umqusozousr.js',
  });
  const {
    t
  } = useI18n();
  const {
    notification,
    createErrorModal
  } = useMessage();
  const {
    prefixCls
  } = useDesign('login');
  const userStore = useUserStore();
  const {
    setLoginState,
    getLoginState
  } = useLoginState();

  const {
    getFormRules
  } = useFormRules();

  const formRef = ref();
  const thirdModalRef = ref();
  const loading = ref(false);
  let rememberMe = ref(false);

  let formData = reactive({
    tenantCode: null,
    organizationId: null,
    organizationName: undefined,
    account: '',
    password: '',
    inputCode: '',
  });
  const randCodeData = reactive({
    randCodeImage: '',
    requestCodeSuccess: false,
    checkKey: null,
  });
  const {
    validForm
  } = useFormValid(formRef);

  //onKeyStroke('Enter', handleLogin);

  const getShow = computed(() => unref(getLoginState) === LoginStateEnum.LOGIN);

  function enter() {
    console.log(123);
  }

  window.addEventListener('keydown', handkeyCode, true);

  function handkeyCode(e) {
    if (e.keydown == 13) {
      let activeEl = document.activeElement;
      let nextEl = activeEl.nextElementSibling;
      nextEl && nextEl.focus();
    }
  }
   async function handleLogin() {
    const data = await validForm();

    if (!data) return;
    try {
      loading.value = true;
      // 获取当前用户的登录组织
      let organizationName = null;
      organization.organizationList.forEach(item => {
        if (formData.organizationId == item.value) {
          organizationName = item.label;
        }
      });
      const {
        userInfo
      } = await userStore.login(
        toRaw({
          password: data.password,
          tenantCode: data.tenantCode,
          organizationId: formData.organizationId,
          organizationName: organizationName,
          username: data.account,
          captcha: data.inputCode,
          checkKey: randCodeData.checkKey,
          mode: 'none', //不要默认的错误提示
          rememberMe:rememberMe
        })
      );
      if (userInfo) {
        notification.success({
          message: t('sys.login.loginSuccessTitle'),
          description: `${t('sys.login.loginSuccessDesc')}: ${userInfo.realname}`,
          duration: 3,
        });
      }
    } catch (error) {
      notification.error({
        message: t('sys.api.errorTip'),
        description: error.message || t('sys.api.networkExceptionMsg'),
        duration: 3,
      });
      loading.value = false;

      //update-begin-author:taoyan date:2022-5-3 for: issues/41 登录页面，当输入验证码错误时，验证码图片要刷新一下，而不是保持旧的验证码图片不变
      // handleChangeCheckCode();
      //update-end-author:taoyan date:2022-5-3 for: issues/41 登录页面，当输入验证码错误时，验证码图片要刷新一下，而不是保持旧的验证码图片不变
    }
  }

  // function handleChangeCheckCode() {
  //   formData.inputCode = '';
  //   //TODO 兼容mock和接口，暂时这样处理
  //   randCodeData.checkKey = 1629428467008; //new Date().getTime();
  //   getCodeInfo(randCodeData.checkKey).then((res) => {
  //     randCodeData.randCodeImage = res;
  //     randCodeData.requestCodeSuccess = true;
  //   });
  // }
  let tenantList: any = reactive([]);
  //初始化租户列表
  function initGetTenantList() {
    getTenantList().then((res) => {
      let list = res.records;
      //tenantList=[]
      list.forEach((item) => {
        tenantList.push({
          value: item.id,
          label: item.code
        });
      });
    });
  }
  initGetTenantList();
  let organization = reactive({
    organizationList: [{
      value: '',
      label: '无'
    }],
  });

  //获取组织列表
  function getOrganizationList(val) {
    // 每次输入 先清空组织  避免push相同组织
    organization.organizationList = [{
      value: '',
      label: '无'
    }];
    if(!formData.tenantCode || !formData.account) {
      // 实时检索组织编码和用户名  不符就清空原有的组织id和name
      formData.organizationId = null;
      formData.organizationName = undefined;
      return
    };
    queryOrganizationByTenantAndUser({
      tenantCode: formData.tenantCode,
      userName : formData.account
    }).then((res) => {
      if (res == null) {
        // 获取不到组织就清空原有的组织id和name
        formData.organizationId = null;
        formData.organizationName = undefined;
      } else {
        res.forEach((item) => {
          organization.organizationList.push({
            value: item.id,
            label: item.organizationName
          });
        });
      }
    });
  }

  //获取组织列表
  async function dropdownVisibleChange() {
    organization.organizationList = reactive([{
      value: '',
      label: '无'
    }]);
    if (formData.tenantCode == null) {
      notification.error({
        message: '提示',
        description: '请选择租户编码',
        duration: 3,
      });
      return;
    }
    let res = await basBusinessOrganization({
      tenantCode: formData.tenantCode
    });
    if (res.length > 0) {
      res.forEach((item) => {
        organization.organizationList.push({
          value: item.id,
          label: item.organizationName
        });
      });
    } else {
      organization.organizationList = reactive([]);
    }

  }

  function handleChangeOrganization(selectedObj) {
    if (selectedObj) {
      formData.organizationId = selectedObj.value;
      formData.organizationName = selectedObj.label;
    }

  }
  function changeRemember(event) {
    localStorage.set('setStoreRemember',event.target.checked)
    // window.localStorage.setItem('setStoreRemember',event.target.checked)
    userStore.setRemember(event.target.checked)
    rememberMe.value = event.target.checked;
  }
  /**
   * 第三方登录
   * @param type
   */
  // function onThirdLogin(type) {
  //   thirdModalRef.value.onThirdLogin(type);
  // }
  onMounted(() => {    
      if(typeof localStorage.get('setStoreRemember') !== null) {
        rememberMe.value = localStorage.get('setStoreRemember');
      } else {
        rememberMe.value = false
      }
    // 获取储存的登录信息
    const loginParams = localStorage.get('loginParams');    
    
    if (rememberMe.value && loginParams) {
    const {tenantCode,username,organizationId,organizationName,password} = loginParams;
      formData.tenantCode = tenantCode || null;
      formData.account = username || "";
      formData.organizationId = organizationId || null;
      formData.organizationName = organizationName || "";
      formData.password = password || "";
      formData.inputCode = null;
      if (formData.tenantCode) {
        getOrganizationList();
      }
    }
  //初始化验证码
  // handleChangeCheckCode();
  });

</script>
